# _*_ coding: utf-8 _*_
import sys
from urllib3.util import parse_url
from PyQt5 import QtWidgets
from PyQt5 import QtCore
from PyQt5 import QtGui
# 自定义
from widgets import CustomMenuBar
from widgets import DownloadButton
from widgets import LinkBar
from widgets import CustomProgress
from widgets import CustomStatusbar
# 线程
from core import QNovelThread
from module import CatalogSpider
# 工具
from tools import OperPath
# 配置
from config import SAVE_TO_PATH
from config import THREAD_NUMBER


class Example(QtWidgets.QMainWindow):
    '''测试'''
    # 目录爬虫
    _CatalogSpider = CatalogSpider()
    def __init__(self, parent=None):
        super(Example, self).__init__(parent)
        # 菜单栏
        self.menubar = None
        # 状态栏
        self.statusbar = None
        # 下载按钮
        self.downloadBtn = None
        # 链接文本框
        self.linkBar = None
        # 进度条
        self.progress = None
        # 线程列表
        self.workers = None
        # 存储路径
        self.toDir = None


    def initUI(self) -> None:
        '''初始化UI'''
        # 初始化自定义部件
        self.initWidgets()
        self.addWidgets()
        # 初始化应用
        self.setFixedSize(400, 130)
        self.setWindowTitle("Demo")
        self.setWindowIcon(QtGui.QIcon("./icon.png"))
        self.show()


    def initWidgets(self) -> None:
        '''初始化部件'''
        self.menubar = CustomMenuBar(url="https://www.xbiquge.la/")
        self.statusbar = CustomStatusbar()
        self.linkBar = LinkBar(self)
        self.downloadBtn = DownloadButton(self.linkBar, self)
        self.progress = CustomProgress(self)
        # 按钮绑定功能
        self.downloadBtn.clicked.connect(self.download)


    def addWidgets(self) -> None:
        '''添加小部件'''
        self.setMenuWidget(self.menubar)
        self.setStatusBar(self.statusbar)


    def keyPressEvent(self, a0: QtGui.QKeyEvent) -> None:
        '''Esc关闭窗口'''
        if a0.key() == QtCore.Qt.Key.Key_Escape:
            self.close()


    def lineEditContentIfIllegal(self, content: str) -> bool:
        '''判断文本框内容是否非法'''
        scheme, auth, host, port, path, query, fragment = parse_url(content)
        if scheme is None:
            return False

        if host is None:
            return False

        return True



    def download(self) -> None:
        '''下载'''
        # 判断内容是否非法
        reply = self.linkBar.text()
        if not self.lineEditContentIfIllegal(reply):
            self.statusbar.showMessage("非法参数")
            return

        # 爬取目录
        self._CatalogSpider.url = reply
        self._CatalogSpider.send()
        self._CatalogSpider.parse()

        # 创建存储路径
        self.toDir = OperPath.exists(SAVE_TO_PATH, self._CatalogSpider.title)

        # 初始化进度条, 线程计数器
        self.progress.setMaxStep(self._CatalogSpider.length)
        QNovelThread.counter.reload(self._CatalogSpider.length)

        # 队列集添加数据
        for novelInfo in self._CatalogSpider.results:
            QNovelThread.dataQueue.put(novelInfo)

        # 多线程下载
        self.workers = QNovelThread(self.toDir, THREAD_NUMBER)
        # 线程槽绑定
        self.workers.statusSignal.connect(self.statusbar.showMessage)
        self.workers.progressSignal.connect(self.progress.setValue)
        self.workers.btnStateSignal.connect(self.downloaded)
        self.workers.start()

        # 按钮不可点击
        self.downloadBtn.setEnabled(False)


    def downloaded(self) -> None:
        '''任务完成后'''
        del self.workers
        self.downloadBtn.setEnabled(True)


if __name__ == "__main__":
    # 测试路径 -> https://www.xbiquge.la/81/81806/
    app = QtWidgets.QApplication(sys.argv)
    ex = Example()
    ex.initUI()
    sys.exit(app.exec_())